<?php
namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use App\Models\SignModel;
use App\Models\SignPointModel;
use App\Models\PointChangeModel;
use App\Models\UserModel;

class SignController extends Controller{

    public function __construct()
    {
        $this->middleware('user_login');
    }

    //签到
    public function sign(SignModel $signMoel,SignPointModel $signPointModel,PointChangeModel $pointChangeModel,UserModel $userModel){

        $signPoint = $signPointModel->first();

        $sign = $signMoel->where('user_id',auth('user_api')->user()->id)->orderBy('sign_time','desc')->first();
        if(!empty($sign)&&$sign->sign_time == date("Y-m-d")){
            return returnMsg(400,'你今天已经签到，请明天再来');
        }elseif($sign->sign_time == date('Y-m-d',strtotime('-1 day'))){//昨天已签到，连续签到处理

            $num = $sign->num+1;
            $point = $signPoint->point;
            if ($sign->num == 7) {//连续签到7天，每7天清零
                $num = 0;//连续签到次数
                $point = $point + $signPoint->reward_point;//加上额外奖励积分数
            }

        }else{
            $num =1;
            $point = $signPoint->point;
        }

        //更新积分记录表
        $pointChangeModel->point = $point;
        $pointChangeModel->point_info = '签到获得积分';
        $pointChangeModel->point_type = 1;
        $pointChangeModel->user_id = auth('user_api')->user()->id;
        $pointChangeModel->save();
        //更新用户数据
        $userModel->point =$point;
        $userModel->user_id = auth('user_api')->user()->id;
        $userModel->save();

        $signMoel->sign_time = date("Y-m-d");
        $signMoel->user_id = auth('user_api')->user()->id;
        $signMoel->num = $num;
        $signMoel->point = $point;
        $signMoel->sign_time = time();

        $res = $signMoel->save();
        if($res){
            return returnMsg(0,'签到成功');
        }
    }

    //获取我的签到
    public function my_sign(Request $request,SignModel $signModel){

        $time = $request->input('time');
        $start=date('Y-m-01',strtotime($time));//获取指定月份的第一天
        $end=date('Y-m-t',strtotime($time)); //获取指定月份的最后一天

        $signModel
            ->select([
                'sign_time'
            ])
            ->where('user_id',auth('user_api')->user()->id)
            ->whereBetween('create_time',[strtotime($start),strtotime($end)])
            ->first();

    }

}